<?php

namespace app\admin\model;

use think\Model;
use think\Db;
use think\Env;
use think\Config;

class Ocation extends Model
{
    // 表名
    public $name = 'ocation';
    public $prefix_new = 'fa_';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $deleteTime = 'delete_time';
    public $data;

    // 全局查询范围，过滤已删除记录
    protected function base($query)
    {
        $query->where('delete_time', 'null');
    }
    // 定义允许写入的字段
    protected $field = [
        'id', 'pid', 'name', 'address', 'longitude', 'latitude', 'status',
        'create_time', 'update_time', 'delete_time', 'rel_type', 'rel_id',
        'address_lv', 'address_lv_octionlevel', 'school_location_type', 'entvirt',
        'ocation_type', 'starttime', 'endtime', 'intro', 'cover', 'image',
        'weekdays', 'daytime', 'classtime', 'classsleeptime', 'classes_per_week',
        'disable_week_range', 'disable_week_time', 'max_number', 'schedule_data',
        'province_id', 'city_id', 'district_id'
    ];

    /**
     * 获取指定教学点的所有子教学点ID（递归）
     *
     * @param int|string|array $parentId 父教学点ID，支持逗号分隔字符串或数组
     * @param bool $includeSelf 是否包含自身ID
     * @return array 所有子教学点ID数组
     */
    public static function getChildOcationIds($parentId, $includeSelf = false)
    {
        $childIds = [];
        // 支持逗弦分隔字符串或数组
        if (is_string($parentId) && strpos($parentId, ',') !== false) {
            $parentId = explode(',', $parentId);
        }
        // 获取直接子教学点
        $directChildren = self::where('pid', 'in', (array)$parentId)
            ->where('status', 1)
            ->column('id');
        foreach ($directChildren as $childId) {
            $childIds[] = $childId;
            // 递归获取子教学点的子教学点
            $grandChildIds = self::getChildOcationIds($childId);
            $childIds = array_merge($childIds, $grandChildIds);
        }
        if ($includeSelf) {
            foreach ((array)$parentId as $pid) {
                array_unshift($childIds, $pid);
            }
        }
        return $childIds;
    }

    public function getAddress_lvTextAttr($value, $data)
    {
        if ($value) {
            $nn = preg_split("/,/", $value);
        } else {
            $nn = array();
        }
        $s = array();
        for ($i = 0; $i < count($nn); $i++) {
            if ($nn[$i] == "") continue;
            $r = Model("addresslv")->get(array("id" => $nn[$i]));
            if ($r) $s[] = $r['name'];
        }
        return join(",", $s);
    }

    public function getOcation_idTextAttr($value, $data = [])
    {
        if ($value) {
            $nn = preg_split("/,/", $value);
        } else {
            $nn = array();
        }
        $s = array();
        for ($i = 0; $i < count($nn); $i++) {
            if ($nn[$i] == "") continue;
            $data = json_decode(json_encode($data), true);
            $r = Db::name("Ocation")->find(array("id" => $nn[$i]));
            if ($r) $s[] = $r['name'];
        }
        return join(",", $s);
    }

    public function getAddress_lv_octionlevel_TextAttr($value, $data = array())
    {
        $s = array();
        $content = array(
            "1" => "一级教学点",
            "2" => "二级教学点",
            "3" => "三级教学点",
            "4" => "上课教室",
        );
        if ($value) {
            $nn = preg_split("/,/", $value);
        } else {
            $nn = array();
        }
        for ($i = 0; $i < count($nn); $i++) {
            if ($nn[$i] == "") continue;
            if (isset($content[$nn[$i]])) $s[] = $content[$nn[$i]];
        }
        return join(",", $s);
    }

    public function getOction_typeTextAttr($value, $data = array())
    {
        $s = array();
        $content = array(
            "1" => "标准类",
            "2" => "书画类",
            "3" => "肢体类",
            "4" => "综合类",
        );
        if ($value) {
            $nn = preg_split("/,/", $value);
        } else {
            $nn = array();
        }
        for ($i = 0; $i < count($nn); $i++) {
            if ($nn[$i] == "") continue;
            if (isset($content[$nn[$i]])) $s[] = $content[$nn[$i]];
        }
        return join(",", $s);
    }

    public function getSchool_location_typeTextAttr($value, $data = array())
    {
        $s = array();
        $content = array(
            "1" => "校内",
            "2" => "校外",
        );
        if ($value) {
            $nn = preg_split("/,/", $value);
        } else {
            $nn = array();
        }
        for ($i = 0; $i < count($nn); $i++) {
            if ($nn[$i] == "") continue;
            if (isset($content[$nn[$i]])) $s[] = $content[$nn[$i]];
        }
        return join(",", $s);
    }

    protected function setAddress_lvAttr($value)
    {
        return $value && is_array($value) ? join(",", $value) : $value;
    }

    protected function setSchool_location_typeAttr($value)
    {
        return $value && is_array($value) ? join(",", $value) : $value;
    }

    public function getRel_typeTextAttr($value, $data)
    {
        $s = array();
        $content = array(
            "1" => "学校",
            "2" => "社区",
        );
        if ($value) {
            $nn = preg_split("/,/", $value);
        } else {
            $nn = array();
        }
        for ($i = 0; $i < count($nn); $i++) {
            if ($nn[$i] == "") continue;
            if (isset($content[$nn[$i]])) $s[] = $content[$nn[$i]];
        }
        return join(",", $s);
    }


    public function getOcation_typeTextAttr($value, $data = array())
    {
        if ($value == "") return "标准";
        $s = array();
        $content = array(
            "1" => "标准",
            "2" => "书画",
            "3" => "肢体",
            "4" => "综合",
        );
        if ($value) {
            $nn = preg_split("/,/", $value);
        } else {
            $nn = array();
        }
        for ($i = 0; $i < count($nn); $i++) {
            if ($nn[$i] == "") continue;
            if (isset($content[$nn[$i]])) $s[] = $content[$nn[$i]];
        }
        return join(",", $s);
    }

    public function getRel_idTextAttr($value, $data)
    {
        $s = array();
        $content = [];
        if ($value) {
            $nn = preg_split("/,/", $value);
        } else {
            $nn = array();
        }
        for ($i = 0; $i < count($nn); $i++) {
            if ($nn[$i] == "") continue;
            if (isset($content[$nn[$i]])) $s[] = $content[$nn[$i]];
        }
        return join(",", $s);
    }

    public function getParentOcations($ocation_id)
    {
        $parentTeachingOcationId = $this->where('id', $ocation_id)->value('pid');
        $topTeachingOcationId = 0;
        $areaTeachingOcationId = 0;

        $parentTeachingOcationName = '';
        $topTeachingOcationName = '';
        $areaTeachingOcationName = '';

        if ($parentTeachingOcationId) {
            // 获取直接父级教学点名称
            $parentTeachingOcationName = $this->where('id', $parentTeachingOcationId)->value('name');

            // 向上查找address_lv_octionlevel=1的教学点记录
            $currentId = $parentTeachingOcationId;
            while ($currentId > 0) {
                $currentOcation = $this->where('id', $currentId)->field('pid, address_lv_octionlevel, name')->find();
                if ($currentOcation && $currentOcation['address_lv_octionlevel'] == 1) {
                    $topTeachingOcationId = $currentId;
                    $topTeachingOcationName = $currentOcation['name'];
                    break;
                }
                $currentId = $currentOcation ? $currentOcation['pid'] : 0;
            }

            // 如果没有找到address_lv_octionlevel=1的记录，则继续向上查找直到顶级
            if ($topTeachingOcationId == 0) {
                $currentId = $parentTeachingOcationId;
                while ($currentId > 0) {
                    $currentOcation = $this->where('id', $currentId)->field('pid, name, address_lv_octionlevel')->find();
                    if (!$currentOcation || $currentOcation['pid'] == 0) {
                        $topTeachingOcationId = $currentId;
                        $topTeachingOcationName = $currentOcation ? $currentOcation['name'] : '';
                        break;
                    }
                    $currentId = $currentOcation['pid'];
                }
            }

            // 向上查找address_lv_octionlevel=0的教学点记录
            $currentId = $parentTeachingOcationId;
            while ($currentId > 0) {
                $currentOcation = $this->where('id', $currentId)->field('pid, address_lv_octionlevel, name')->find();
                if ($currentOcation && $currentOcation['address_lv_octionlevel'] == 0) {
                    $areaTeachingOcationId = $currentId;
                    $areaTeachingOcationName = $currentOcation['name'];
                    break;
                }
                $currentId = $currentOcation ? $currentOcation['pid'] : 0;
            }

            // 如果没有找到address_lv_octionlevel=0的记录，则继续向上查找直到顶级
            if ($areaTeachingOcationId == 0) {
                $currentId = $parentTeachingOcationId;
                while ($currentId > 0) {
                    $currentOcation = $this->where('id', $currentId)->field('pid, name, address_lv_octionlevel')->find();
                    if (!$currentOcation || $currentOcation['pid'] == 0) {
                        $areaTeachingOcationId = $currentId;
                        $areaTeachingOcationName = $currentOcation ? $currentOcation['name'] : '';
                        break;
                    }
                    $currentId = $currentOcation['pid'];
                }
            }
        }

        return [
            'parentTeachingOcationId' => $parentTeachingOcationId,
            'topTeachingOcationId' => $topTeachingOcationId,
            'areaTeachingOcationId' => $areaTeachingOcationId,
            'parentTeachingOcationName' => $parentTeachingOcationName,
            'topTeachingOcationName' => $topTeachingOcationName,
            'areaTeachingOcationName' => $areaTeachingOcationName,
        ];
    }

    function getOcationInfo($id,$city)
    {

        $info = $this->where('id', $id)->find();
        if ($info == null) {

            $location = $this->getLocation($city."政府");
            $info =array("id"=>$id,"latitude"=>$location['latitude'],"longitude"=>$location['longitude']);
        } else {
            if (!isset($info['latitude']) || !isset($info['longitude'])) {
                $info = $this->getLocation($city,$info['address'], $info['id']);
            }
        }

        return $info;
    }


    function getLocation($city="",$address="", $id=null)
    {
        //$ak = Config::get('baidu.AI_BAIDU_MAP_KEY_SERVICE');
        $ak = Env::get("ai.AI_BAIDU_MAP_KEY_SERVICE");
        //$ak ="aBIfRNb8MimBirL5RrjJn1WKDGs0jVQE";
        $url = 'https://api.map.baidu.com/reverse_geocoding/v3/?address=' . urlencode($city.$address) . '&output=json&ak=' . $ak;

        $apiUrl = "https://api.map.baidu.com/geocoding/v3/?" . http_build_query([
                "address" => $city.$address,
                "city" => urlencode($city),
                "output" => 'json',
                "ak" => $ak,
                "callback" => "", // 若不需要JSONP，留空即可
            ]);

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true, // 结果返回为字符串，不直接输出
            CURLOPT_SSL_VERIFYPEER => false, // 开发阶段关闭SSL验证（生产环境建议开启）
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_TIMEOUT => 10, // 超时时间（秒）
        ]);

        $res = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($res, true);
        if($data['status']==240){
            //{"status":240,"message":"APP 服务被禁用"} 百度地图逆地理编码接口调用失败，错误状态码 240 表示 “APP 服务被禁用
            return array("latitude"=>0,"longitude"=>0);
        }

        $location = $data['result']['location'];
        $info = [
            'latitude' => $location['lat'],
            'longitude' => $location['lng'],
        ];

        if($id!=null) {
            $this->where('id', $id)->where(function ($query) use ($info) {
                $query->where('latitude', 'null')->whereOr('longitude', 'null');
            })->update($info);
        }
        return $info;
    }
}